/* eslint-disable @typescript-eslint/no-unused-vars */
//路由守卫

import type { Router } from 'vue-router';
import { sessionCache } from '@/utils/cache/sessionCache';
import { constant } from '@/utils/cache/sessionCacheEnums';
import { authStore } from '@/stores/authStore';
import router, {setupDynamicRoutes} from '@/router/index';
import { userAuthProcessStore } from '@/stores/userAuthProcess';
import { moduleStore } from '@/stores/moduleStore';
const routeGradesInit = function(routes : Router){
    initGrades(routes);
    authGrades(routes);
}

const whiteRouteUrls = ["/" ,"/login","/sign",import.meta.env.VITE_APP_LOGIN_PATH]; //访问不需要校验token的 路由地址

//通用配置
const initGrades = (routes : Router) =>{
    //前置处理
    routes.beforeEach(async (to) =>{
      const auth = authStore();
      const moduleAuth = moduleStore();
        if(whiteRouteUrls.indexOf(to.fullPath) < 0){
          //校验token是否存在
          if(!auth.getToken){
              auth.CLEAR_USERINFO();
              moduleAuth.clearModuleMap();
              router.replace({path:import.meta.env.VITE_APP_LOGIN_PATH || '/'})
              return Promise.reject();
          }
          //校验是否需要重新加载userInfo
          if(!auth.userInfo || !auth.userInfo.id){
            const loginStore = userAuthProcessStore();
            await loginStore.Get_UserInfo().catch(()=>{
              return Promise.reject();
            })
          }
          if (router.getRoutes().length === 3) {
            await setupDynamicRoutes();
            return to.fullPath; // 重定向到当前路径，触发新路由匹配
          }
        console.log("USE_TOKEN:" +  auth.getToken)
        }
        return true;
    })
    //后置
    routes.afterEach( async (to,from)=>{
      console.log("afterEach",to,from)
        cacheRouterPushPath(to.path,from.path);
        setWebTitle(to.meta.title as unknown as string);

        return true;
    })
}

//路由权限加载
const authGrades = (routes : Router) => {
  console.log(routes);
}

//设置网页title
const setWebTitle =(title : string) =>{
  document.title = title ? title + ' | idoo' : 'idoo';
}

//缓存路由 跳转前后路径
const cacheRouterPushPath = (toPath : string , fromPath : string)=>{
  //跳转登录界面时，清空session缓存
  if(toPath.indexOf('/login') != 0){
    sessionCache.remove(constant.ROUTE_CACHE_FROM);
  }else{
    sessionCache.put(constant.ROUTE_CACHE_FROM,fromPath);
  }
}

export  { routeGradesInit }
